<?php
// +----------------------------------------------------------------------
// | Function：自定义错误日志类
// +----------------------------------------------------------------------
// | Copyright (c) 多享 2022
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: xiaochun <3204016924@qq.com>
// +----------------------------------------------------------------------

namespace yvhsse;


use Exception;
use think\App;
use think\exception\DbException;
use think\exception\ErrorException;
use think\Request;

class DebugLog
{

    protected $config = [
        'time_format' => ' c ',
        'single'      => false,
        'file_size'   => 2097152,
        'path'        => RUNTIME_PATH . 'exception/',
        'apart_level' => [],
        'max_files'   => 0,
        'json'        => false,
    ];

    private static $_instance;

    // 实例化并传入参数
    public function __construct($config = [])
    {
        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }
    }

    /**
     * 初始化
     * @param array $config 配置参数
     * @return DebugLog
     * @author: xiaochun <3204016924@qq.com>
     * @Date  ：2023-07-18 10:48
     */
    public static function instance(array $config = [])
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new static($config);
        }
        return self::$_instance;
    }

    /**
     * 设置日志目录
     * @param string $path
     * @author: xiaochun <3204016924@qq.com>
     * @Date  ：2023-07-18 10:44
     */
    public static function setPath(string $path)
    {
        if (substr($path, 0, -1) != '/') {
            $path .= '/';
        }
        is_null(self::$_instance) && self::instance();
        self::$_instance->config['path'] = RUNTIME_PATH . $path;
    }

    /**
     * Function：记录日志
     * @param array|object|string|null $msg       消息记录
     * @param string                   $path
     * @param string                   $appendMsg 补充说明
     * @author: xiaochun <3204016924@qq.com>
     * @Date  ：2022-11-23 13:50
     */
    public static function log($msg, string $appendMsg = '', string $path = '')
    {
        is_null(self::$_instance) && self::instance();
        if ($path) {
            self::setPath($path);
        }
        $param = debug_backtrace();
        $log[] = '来源文件:' . $param[0]['file'];
        $log[] = '来源方法:' . $param[1]['function'];
        $log[] = '来源行数：' . $param[0]['line'];
        $log[] = '记录数据：' . (is_array($msg) ? var_export($msg, true) : $msg);
        if ($appendMsg) {
            array_unshift($log, '补充说明：' . $appendMsg);
        }
        self::$_instance->write($log, self::$_instance->getMasterLogFile());
    }

    /**
     * Function：自定义异常美化工具
     * @param Exception|string|array $msg       异常消息
     * @param string                 $path      日志保存路径
     * @param string                 $appendMsg 【异常抛出时】补充说明
     * @author: xiaochun <3204016924@qq.com>
     * @Date  ：2022-11-11 14:58
     */
    public static function record($msg, string $appendMsg = '', string $path = '')
    {
        is_null(self::$_instance) && self::instance();
        if ($path) {
            self::setPath($path);
        }
        $param = debug_backtrace();
        if ($msg instanceof Exception) {
            $exception = $param[0]['args'][0];
            $function = $param[1]['function'];
            $line = $msg->getLine();
            $file = $msg->getFile();
            $classPath = '';
            if ($exception instanceof ErrorException) {
                $trace = $exception->getTrace();
                if (isset($trace[1])) {
                    //$line = $trace[1]['line'];
                    $function = $trace[1]['function'] ?? '';
                    $classPath = $trace[1]['class'] ?? '';
                    if (isset($trace[1]['file'])) {
                        $file = $trace[1]['file'];
                    }
                }
            }
            $log[] = '来源文件：' . $file;
            $log[] = '来源类名：' . $classPath;
            $log[] = '来源方法：' . $function;
            $log[] = '错误行数：' . $line;
            $log[] = '错误代码：' . $msg->getCode();
            $log[] = '错误消息：' . $msg->getMessage();
            //$log[] = '上级异常：' . $msg->getPrevious();
            //$log[] = '异常追踪：' . var_export($msg->getTrace(), true);
        } else {
            $log[] = '来源文件:' . $param[0]['file'];
            $log[] = '来源方法:' . $param[1]['function'];
            $log[] = '来源行数：' . $param[0]['line'];
            $log[] = '错误代码：' . 0;
            $log[] = '错误消息：' . (is_array($msg) ? var_export($msg, true) : $msg);
            //$log[] = '上级异常：';
            //$log[] = '异常追踪：';
        }
        if($msg instanceof DbException){
            $log[] = 'sql:'.db()->getLastSql();
        }
        if ($appendMsg) {
            array_unshift($log, '补充说明：' . $appendMsg);
        }
        self::$_instance->write($log, self::$_instance->getMasterLogFile());
    }

    /**
     * 日志写入接口
     * @access public
     * @param array $log    日志信息
     * @param bool  $append 是否追加请求信息
     * @return bool
     */
    public function save(array $log = [], $append = false)
    {
        $destination = $this->getMasterLogFile();

        $info = [];
        foreach ($log as $type => $val) {

            foreach ($val as $msg) {
                if (!is_string($msg)) {
                    $msg = var_export($msg, true);
                }

                $info[$type][] = $this->config['json'] ? $msg : '[ ' . $type . ' ] ' . $msg;
            }

            if (!$this->config['json'] && (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level']))) {
                // 独立记录的日志级别
                $filename = $this->getApartLevelFile($path, $type);

                $this->write($info[$type], $filename, true, $append);
                unset($info[$type]);
            }
        }

        if ($info) {
            return $this->write($info, $destination, false, $append);
        }

        return true;
    }

    /**
     * 获取主日志文件名
     * @access public
     * @return string
     */
    protected function getMasterLogFile()
    {
        if ($this->config['single']) {
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';

            $destination = $this->config['path'] . $name . '.log';
        } else {
            $cli = PHP_SAPI == 'cli' ? '_cli' : '';

            if ($this->config['max_files']) {
                $filename = date('Ymd') . $cli . '.log';
                $files = glob($this->config['path'] . '*.log');

                try {
                    if (count($files) > $this->config['max_files']) {
                        unlink($files[0]);
                    }
                } catch (Exception $e) {
                }
            } else {
                $filename = date('Ym') . DIRECTORY_SEPARATOR . date('d') . $cli . '.log';
            }

            $destination = $this->config['path'] . $filename;
        }
        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);
        if (IS_CLI) {
            // 场景适用于命令行,且存在www用户和www组
            $userName = $groupName = 'www';
            $userInfo = (posix_getpwnam($userName));
            $groupInfo = (posix_getgrnam($groupName));
            if ($userInfo && $groupInfo) {
                $status = true;
                $runtimePath = realpath(RUNTIME_PATH);
                // 用递归来改目录权限
                do {
                    if ($runtimePath != $path) {
                        chgrp($path, 'www');
                        chown($path, 'www');
                        $path = dirname($path);
                    } else {
                        $status = false;
                    }
                } while ($status);
                // 文件不存在时创建,并修改文件权限
                if (!file_exists($destination)) {
                    file_put_contents($destination, '');
                    chgrp($destination, 'www');
                    chown($destination, 'www');
                    chmod($destination, 0644);
                }
            }
        }
        return $destination;
    }

    /**
     * 获取独立日志文件名
     * @access public
     * @param string $path 日志目录
     * @param string $type 日志类型
     * @return string
     */
    protected function getApartLevelFile($path, $type)
    {
        $cli = PHP_SAPI == 'cli' ? '_cli' : '';

        if ($this->config['single']) {
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';

            $name .= '_' . $type;
        } elseif ($this->config['max_files']) {
            $name = date('Ymd') . '_' . $type . $cli;
        } else {
            $name = date('d') . '_' . $type . $cli;
        }

        return $path . DIRECTORY_SEPARATOR . $name . '.log';
    }

    /**
     * 日志写入
     * @access protected
     * @param array  $message     日志信息
     * @param string $destination 日志文件
     * @param bool   $apart       是否独立文件写入
     * @param bool   $append      是否追加请求信息
     * @return bool
     */
    protected function write($message, $destination, $apart = false, $append = false)
    {
        // 检测日志文件大小，超过配置大小则备份日志文件重新生成
        $this->checkLogSize($destination);

        // 日志信息封装
        $info['timestamp'] = date($this->config['time_format']);

        foreach ($message as $type => $msg) {
            $info[$type] = is_array($msg) ? implode("\r\n", $msg) : $msg;
        }

        if (PHP_SAPI == 'cli') {
            $message = $this->parseCliLog($info);
        } else {
            // 添加调试日志
            $this->getDebugLog($info, $append, $apart);
            $message = $this->parseLog($info);
        }

        return error_log($message, 3, $destination);
    }

    /**
     * 检查日志文件大小并自动生成备份文件
     * @access protected
     * @param string $destination 日志文件
     * @return void
     */
    protected function checkLogSize($destination)
    {
        if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
            try {
                rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination));
            } catch (Exception $e) {
            }
        }
    }

    /**
     * CLI日志解析
     * @access protected
     * @param array $info 日志信息
     * @return string
     */
    protected function parseCliLog($info)
    {
        if ($this->config['json']) {
            $message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
        } else {
            $now = $info['timestamp'];
            unset($info['timestamp']);

            $message = implode("\r\n", $info);

            $message = "[{$now}]" . $message . "\r\n";
        }

        return $message;
    }

    /**
     * 解析日志
     * @access protected
     * @param array $info 日志信息
     * @return string
     */
    protected function parseLog($info)
    {
        $request = Request::instance();
        $requestInfo = [
            'ip'     => $request->ip(),
            'port'   => $request->server('REMOTE_PORT'),
            'method' => $request->method(),
            'host'   => $request->host(),
            'uri'    => $request->url(),
        ];

        if ($this->config['json']) {
            $info = $requestInfo + $info;
            return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
        }

        array_unshift($info, "[{$info['timestamp']}] {$requestInfo['ip']}:{$requestInfo['port']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}");
        array_unshift($info, "---------------------------------------------------------------");
        unset($info['timestamp']);

        return implode("\r\n", $info) . "\r\n";
    }

    protected function getDebugLog(&$info, $append, $apart)
    {
        if (App::$debug && $append) {

            if ($this->config['json']) {
                // 获取基本信息
                $runtime = round(microtime(true) - THINK_START_TIME, 10);
                $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';

                $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);

                $info = [
                        'runtime' => number_format($runtime, 6) . 's',
                        'reqs'    => $reqs . 'req/s',
                        'memory'  => $memory_use . 'kb',
                        'file'    => count(get_included_files()),
                    ] + $info;

            } elseif (!$apart) {
                // 增加额外的调试信息
                $runtime = round(microtime(true) - THINK_START_TIME, 10);
                $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';

                $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);

                $time_str = '[运行时间：' . number_format($runtime, 6) . 's] [吞吐率：' . $reqs . 'req/s]';
                $memory_str = ' [内存消耗：' . $memory_use . 'kb]';
                $file_load = ' [文件加载：' . count(get_included_files()) . ']';

                array_unshift($info, $time_str . $memory_str . $file_load);
            }
        }
    }
}